<template>
  <div v-loading="treeLoading" class="category-tree">
    <el-tree
      lazy
      ref="treeRef"
      accordion
      show-checkbox
      node-key="categoryNo"
      :data="elTree.dataSource"
      :load="loadChildTreeData"
      :props="elTree.defaultProps"
      :check-strictly="true"
      @check="handleClickCheckbox"
    />
    <!--
      check-strictly为true，可以避免三级类编码等同于四级类编码前缀时被错认为勾选三级全量。
      当三级为010101时，如果setCheckedKeys的四级编码集合有01010101时，会被全部勾选该三级下的所有四级类
    -->
  </div>
</template>
<script>
import { eventBus } from '../eventBus';
import { getByParentUuidsService } from '@/api/public';
export default {
  data () {
    return {
      elTree: {
        dataSource: [],
        cloneDataSource: [],
        defaultProps: {
          children: 'children',
          label: 'cateNameAndNoStr',
          disabled: 'disabled',
          isLeaf: 'leaf'
        },
        END_LEVEL: '4',
      },
      treeLoading: false
    }
  },
  created () {
    // 设置回显勾选节点
    eventBus.$on('setCheckedNodes', checkedKeys => {
      this.$refs?.treeRef && this.$refs.treeRef.setCheckedKeys(checkedKeys)
    })
    // 加载树的根节点初始数据
    eventBus.$on('loadRootTreeData', async () => {
      const loadingFn = state => { this.treeLoading = state }
      const retData = await this.getCategoryListByParentUuid(null, loadingFn)
      this.elTree.dataSource = this.assembleCategoryNodeFn(retData);
    })
  },
  methods: {
    // 加载分类子树数据
    loadChildTreeData (node, resolve) {
      if (node.level === 0) return false
      const { categoryUuid } = node.data;
      this.getCategoryListByParentUuid(categoryUuid).then(retData => {
        resolve(this.assembleCategoryNodeFn(retData))
      })
    },
    // 勾选tree节点
    handleClickCheckbox () {
      const checkCateMaps = new Map(this.$refs.treeRef.getCheckedNodes().map(item => [item.categoryNo, item]))
      this.$emit('checkTreeNodes', checkCateMaps)
    },
    // 根据父分类查询子分类
    async getCategoryListByParentUuid (categoryUuid, loadingFn) {
      if (!categoryUuid) categoryUuid = 'systemUuid'
      const data = [categoryUuid]
      const res = await getByParentUuidsService(data, loadingFn)
      return res?.retData
    },
    // 组装分类节点
    assembleCategoryNodeFn (retData = []) {
      return retData.map(item => {
        const { cateNameAndNoStr, categoryUuid, categoryPath, categoryName, categoryNo, levelNum } = item;
        return {
          cateNameAndNoStr,
          categoryUuid,
          categoryPath,
          categoryName,
          categoryNo,
          levelNum,
          disabled: levelNum !== this.elTree.END_LEVEL,
          leaf: levelNum === this.elTree.END_LEVEL
        }
      })
    },
  }
}
</script>
<style lang="less" scoped>
.category-tree {
  border: 1px dashed #ebeef5;
}
</style>
